package com.cmict.data.bpm.controller.admin.task;

import com.cmict.data.framework.common.pojo.CommonResult;
import com.cmict.data.framework.common.pojo.PageResult;
import com.cmict.data.bpm.controller.admin.definition.vo.task.TaskCarbonVO;
import com.cmict.data.bpm.controller.admin.definition.vo.task.TaskVariableCreateReqVO;
import com.cmict.data.bpm.controller.admin.definition.vo.task.TaskVariablePageReqVO;
import com.cmict.data.bpm.controller.admin.task.vo.task.*;
import com.cmict.data.bpm.service.task.BpmTaskService;
import com.cmict.data.bpm.service.task.IFlowableCommentService;
import com.cmict.data.bpm.service.task.IFlowableTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

import java.util.Collection;
import java.util.List;

import static com.cmict.data.framework.common.pojo.CommonResult.success;
import static com.cmict.data.framework.web.core.util.WebFrameworkUtils.getLoginUserId;

@Api(tags = "管理后台 - 流程任务实例")
@RestController
@RequestMapping("/bpm/task")
@Validated
public class BpmTaskController {

    @Resource
    private BpmTaskService taskService;
    @Autowired
    private IFlowableCommentService flowableCommentService;
    @Autowired
    private IFlowableTaskService flowableTaskService;

    @GetMapping("bpm-task-statis")
    @ApiOperation("获取任务统计")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<BpmTaskStatisReqVO> getBpmTaskStatis() {
        BpmTaskTodoPageReqVO pageVoT = new BpmTaskTodoPageReqVO();
        BpmTaskDonePageReqVO pageVoD = new BpmTaskDonePageReqVO();
        int todone = Math.toIntExact(taskService.getTodoTaskPage(getLoginUserId(), pageVoT).getTotal());
        int alreadydone = Math.toIntExact(taskService.getDoneTaskPage(getLoginUserId(), pageVoD).getTotal());
//        Long userId = getLoginUserId();
//        List<TaskCarbonDO> carbonCopy = flowableTaskService.getCarbonTask(userId);
        BpmTaskStatisReqVO statis  = new BpmTaskStatisReqVO();
        statis.setTodone(todone);
        statis.setAlreadydone(alreadydone);
//        statis.setCirculatedone(carbonCopy.size());
        return success(statis);
    }

    @GetMapping("todo-page")
    @ApiOperation("获取 Todo 待办任务分页")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<PageResult<BpmTaskTodoPageItemRespVO>> getTodoTaskPage(@Valid BpmTaskTodoPageReqVO pageVO) {
        return success(taskService.getTodoTaskPage(getLoginUserId(), pageVO));
    }

    /**
     * 批量审批  是否可以发起审批
     * @param idList
     * @return
     */
    @PostMapping("getBatchApprovalStatus")
    @ApiOperation("是否可以发起批量审批")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<Boolean> getBatchApprovalStatus(@RequestBody List<String> idList) {
        return success(taskService.getBatchApprovalStatus(getLoginUserId(), new BpmTaskTodoPageReqVO().setIdList(idList)));
    }

    @GetMapping("done-page")
    @ApiOperation("获取 Done 已办任务分页")
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<PageResult<BpmTaskDonePageItemRespVO>> getDoneTaskPage(@Valid BpmTaskDonePageReqVO pageVO) {
        return success(taskService.getDoneTaskPage(getLoginUserId(), pageVO));
    }

    @GetMapping("/list-by-process-instance-id")
    @ApiOperation(value = "获得指定流程实例的任务列表", notes = "包括完成的、未完成的")
    @ApiImplicitParam(name = "processInstanceId", value = "流程实例的编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<List<BpmTaskRespVO>> getTaskListByProcessInstanceId(
            @RequestParam("processInstanceId") String processInstanceId) {
        return success(taskService.getTaskListByProcessInstanceId(processInstanceId));
    }

    /**
     * 批量审批  流转记录
     * @param processInstanceId
     * @return
     */
    @GetMapping("/batch-approval-by-process-instance-id")
    @ApiOperation(value = "获得批量审批的最新一条任务列表", notes = "包括完成的、未完成的")
    @ApiImplicitParam(name = "processInstanceId", value = "流程实例的编号", required = true, dataTypeClass = String.class)
    @PreAuthorize("@ss.hasPermission('bpm:task:query')")
    public CommonResult<BpmTaskRespVO> getBatchApprovalTaskByProcessInstanceId(
            @RequestParam("processInstanceId") String processInstanceId) {
        return success(taskService.getTaskListByProcessInstanceId(processInstanceId).get(0));
    }

    @PutMapping("/approve")
    @ApiOperation("通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> approveTask(@Valid @RequestBody BpmTaskApproveReqVO reqVO) {
        taskService.approveTask(getLoginUserId(), reqVO);
        return success(true);
    }
    @PutMapping("/batchApprove")
    @ApiOperation("批量通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> batchApproveTask( @RequestBody BpmTaskApproveReqVO reqVO) {
        taskService.batchApproveTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/reject")
    @ApiOperation("不通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> rejectTask(@Valid @RequestBody BpmTaskRejectReqVO reqVO) {
        taskService.rejectTask(getLoginUserId(), reqVO);
        return success(true);
    }
    @PutMapping("/batchReject")
    @ApiOperation("批量不通过任务")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> batchRejectTask( @RequestBody BpmTaskRejectReqVO reqVO) {
        taskService.batchRejectTask(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/update-assignee")
    @ApiOperation(value = "更新任务的负责人", notes = "用于【流程详情】的【转派】按钮")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> updateTaskAssignee(@Valid @RequestBody BpmTaskUpdateAssigneeReqVO reqVO) {
        taskService.updateTaskAssignee(getLoginUserId(), reqVO);
        return success(true);
    }

    @PutMapping("/batch-update-assignee")
    @ApiOperation(value = "批量更新任务的负责人", notes = "用于【流程详情】的【转派】按钮")
    @PreAuthorize("@ss.hasPermission('bpm:task:update')")
    public CommonResult<Boolean> batchUpdateTaskAssignee( @RequestBody BpmTaskUpdateAssigneeReqVO reqVO) {
        taskService.batchUpdateTaskAssignee(getLoginUserId(), reqVO);
        return success(true);
    }

    @ApiOperation(value = "获取可驳回节点列表")
    @GetMapping(value = "/getBackNodes/{taskId}")
    public CommonResult<List<FlowNodeVo>> getBackNode(@PathVariable String taskId) {
        List<FlowNodeVo> nodes = flowableTaskService.getBackNodes(taskId);
        CommonResult<List<FlowNodeVo>> returnVo = success(nodes);
        return returnVo;
    }

    @PostMapping(value = "/doBack")
    @ApiOperation(value = "驳回节点")
    public CommonResult<String> doBackTask(@Valid @RequestBody BackTaskVo params) {
        CommonResult<String> returnVo = flowableTaskService.backTask(params);
        return returnVo;
    }

    @PostMapping(value = "/doBackDist")
    @ApiOperation(value = "驳回节点到起点或上一节点")
    public CommonResult<String> doBackTaskTo(@Valid @RequestBody BackTaskDistVo params) {
        CommonResult<String> returnVo = flowableTaskService.backTask(params);
        return returnVo;
    }

    @PostMapping(value = "/batchDoBackDist")
    @ApiOperation(value = "批量驳回节点到起点或上一节点")
    public CommonResult<String> batchDoBackDist( @RequestBody BackTaskDistVo params) {
        CommonResult<String> returnVo = flowableTaskService.batchBackTask(params);
        return returnVo;
    }

    /**
     * 创建流程抄送
     * @param params
     * @return
     */
    @PostMapping(value = "/carbon-copy")
    @ApiOperation(value = "任务抄送")
    public CommonResult<Long> carbonCopy(@Valid @RequestBody TaskVariableCreateReqVO params) {
        Long variableId = flowableTaskService.createCarbonVariable(params);
        return CommonResult.success(variableId);
    }

    @PostMapping(value = "/batch-carbon-copy")
    @ApiOperation(value = "任务抄送")
    public CommonResult<Long> batchCarbonCopy( @RequestBody TaskVariableCreateReqVO params) {
        Long variableId = flowableTaskService.createBatchCarbonVariable(params);
        return CommonResult.success(variableId);
    }

    /**
     * TODO:
     * 1. 读取抄送我的
     * 2. 完成抄送任务，设置为已读状态
     */

    /**
     * 抄送我的
     * @param
     * @return
     */
    @GetMapping(value = "/carbon-copy")
    @ApiOperation(value = "查询抄送我的")
    public CommonResult<PageResult<TaskCarbonVO>> getMyCarbonTask(@Valid TaskVariablePageReqVO pageReqVO) {
        Long userId = getLoginUserId();
        pageReqVO.setUserId(userId);
        pageReqVO.setStatus(0);
        PageResult<TaskCarbonVO> carbonTask = flowableTaskService.getCarbonTask(pageReqVO);
        return CommonResult.success(carbonTask);
    }


    @DeleteMapping("/batchDelete")
    @ApiOperation("批量删除")
    public CommonResult<Boolean> batchDeleteCarbon(@RequestBody Collection<Long> ids) {
        flowableTaskService.batchDeleteCarbon(ids);
        return CommonResult.success(true);
    }
    /**
     * 完成抄送我的任务
     *
     * @param
     * @return
     */
    @GetMapping(value = "/carbon-copy/{carbonId}")
    @ApiOperation(value = "完成抄送我的任务")
    public CommonResult<Boolean> completeMyCarbonTask(@PathVariable Long carbonId) {
        boolean complete = flowableTaskService.completeCarbonTask(carbonId);
        return CommonResult.success(complete);
    }

    /**
     * 完成抄送我的任务
     *
     * @param
     * @return
     */
    @DeleteMapping(value = "/carbon-copy/{carbonId}")
    @ApiOperation(value = "删除抄送任务")
    public CommonResult<Boolean> deleteCarbonTask(@PathVariable Long carbonId) {
        boolean complete = flowableTaskService.deleteCarbonTask(carbonId);
        return CommonResult.success(complete);
    }
}
